package com.declum.naduvar.locking.client;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Naduvar {

	/**
	 * Constants for describing the Commands
	 */
	protected static final String LEASE_LOCK = "leaselock";
	protected static final String RENEW_LOCK = "renewlock";
	protected static final String RELEASE_LOCK = "releaselock";

	private static Naduvar instance;
	private String naduvarHost;
	private int naduvarPort;

	private Naduvar(String naduvarHost, int naduvarPort) {
		this.naduvarHost = naduvarHost;
		this.naduvarPort = naduvarPort;
	}

	public static Naduvar getInstance(final String host, int port) {
		if (instance == null) {
			instance = new Naduvar(host, port);
		}
		return instance;
	}

	public String getLock(String name, String path) throws IOException {
		String key = null;
		String line;
		Socket socket = connect();
		String header = "";
		PrintWriter writter = getWritter(socket);
		writter.println("name: " + name);
		writter.println("key: " + name);
		writter.println("path: " + path);
		writter.println("type: " + LEASE_LOCK);
		writter.flush();

		DataInput reader = getReader(socket);

		do {
			line = reader.readLine();
			if (line == null) {
				header += "\r\n";
				break;
			}
			header += line + "\r\n";
			
		} while (true);
		socket.close();
		if (header.endsWith("\r\n\r\n")) {
			System.out.println("Proper Header");
		}
		System.out.println(header);
		return key;
	}

	private Socket connect() throws UnknownHostException, IOException {
		Socket socket = new Socket(this.naduvarHost, this.naduvarPort);
		return socket;
	}

	private PrintWriter getWritter(Socket socket) throws IOException {
		PrintWriter writter = new PrintWriter(socket.getOutputStream());
		return writter;
	}

	DataInput getReader(Socket socket) throws IOException {
		DataInputStream in = new DataInputStream(socket.getInputStream());
		return in;
	}

	public static void main(String[] args) throws IOException {
		Naduvar naduvar = Naduvar.getInstance("localhost", 9123);
		naduvar.getLock("clement", "/clement");
	}
}
